#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"

//队列的初始化
void QueueInit(Queue* pq)
{
	assert(pq);

	pq->_front = NULL;
	pq->_back = NULL;
	pq->size = 0;
}

//队列的销毁
void QueueDestroy(Queue* pq)
{
	assert(pq);

	QueueNode* cur = pq->_front;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->_front = NULL;
	pq->_back = NULL;
	pq->size = 0;
}

//入队尾
void QueuePush(Queue* pq, QueueDataType x)
{
	assert(pq);

	//创建新节点
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		perror("QueuePush()::malloc()");
		return;
	}
	newnode->a = x;
	newnode->next = NULL;

	//空队列
	if (pq->size == 0)
	{
		pq->_front = newnode;
		pq->_back = newnode;
	}
	else//非空队列
	{
		pq->_back->next = newnode;
		pq->_back = newnode;
	}

	pq->size++;
}

//出队头
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->size > 0);//队列不能为空

	//队列中只有一个元素
	if (pq->_front == pq->_back)
	{
		free(pq->_front);
		pq->_front = NULL;
		pq->_back = NULL;
	}
	else//队列有多个元素
	{
		QueueNode* next = pq->_front->next;
		free(pq->_front);
		pq->_front = next;
	}
	//QueueNode* next = pq->_front->next;
	//free(pq->_front);
	//pq->_front = next;
	pq->size--;
}

//获取队头元素
QueueDataType GetQueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->size > 0);

	return pq->_front->a;
}

//获取队尾元素
QueueDataType GetQueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->size > 0);

	return pq->_back->a;
}

//获取队列元素个数
int GetQueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

//判空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	
	return pq->size == 0;
}